import { useMemo } from "react";
import { useProject } from "utils/project";
import { useUrlParams, useSetUrlParams } from "utils/url";
export const useProjectsSearchParams = () => {
  const [param, setParam] = useUrlParams(["name", "personId"]);
  return [
    useMemo(
      () => ({
        ...param,
        personId: Number(param.personId) || undefined,
      }),
      [param]
    ),
    setParam,
  ] as const;
};

export const useProjectsQueryKey = () => {
  const [params] = useProjectsSearchParams();
  return ["projects", params];
};

export const useProjectModal = () => {
  const [{ projectCreate }, setProjectCreate] = useUrlParams(["projectCreate"]);
  const [{ editingProjectId }, setEditingProjectId] = useUrlParams([
    "editingProjectId",
  ]);
  const setUrlParams = useSetUrlParams()
  const {data:editingProject,isLoading} = useProject(Number(editingProjectId))
  const open = () => {
    setProjectCreate({projectCreate: true})
  }

  const close = () => {
    setUrlParams({projectCreate:'',editingProjectId:''})
  }

  const startEdit = (id: number) => {
    setEditingProjectId({editingProjectId:id})
  }

  return {
    projectModalOpen: projectCreate==='true' || Boolean(editingProjectId),
    editingProject,
    isLoading,
    open,
    close,
    startEdit
  };
};